import requests
from bs4 import BeautifulSoup
import urllib.request


url = 'http://jandan.net/pic'

for i in range(3):
    print(url)
    req = requests.get(url)
    html = req.text

    soup = BeautifulSoup(html, 'lxml')
    result = soup.find_all('a', class_='view_img_link')

    for link in result:
        link = link.get('href')
        print('downloading', link)
        filename = link.split('/')[-1]

        try:
            urllib.request.urlretrieve('http:' + link, 'pics/' + filename)
        except urllib.error.URLError as e:
            print(e)
            print(filename, 'failed')
        else:
            print(filename, 'saved')

    current_page = soup.find_all('span', class_='current-comment-page')
    current_page = current_page[0].text
    next_page = int(current_page.strip('[]')) - 1

    url = 'http://jandan.net/pic/page-%d' % next_page

